package com.ruoyi.standingbook.maintenance.service.impl;

import com.ruoyi.common.tools.constant.ERecordConstant;
import com.ruoyi.common.tools.excel.MyExcelUtil;
import com.ruoyi.common.tools.excel.base.MyExcelResult;
import com.ruoyi.common.tools.excel.listener.MaintenanceExcelListener;
import com.ruoyi.common.tools.utils.SerialGenerator;
import com.ruoyi.standingbook.maintenance.domain.bo.MaintenanceImportBaseBo;
import com.ruoyi.standingbook.maintenance.domain.vo.MaintenanceImportDetailVo;
import com.ruoyi.standingbook.maintenance.service.IMaintenanceImportBaseService;
import com.ruoyi.standingbook.maintenance.service.IMaintenanceImportDetailService;
import com.ruoyi.standingbook.maintenance.service.IMaintenanceService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@RequiredArgsConstructor
@Service
public class MaintenanceExcelService {

    private final IMaintenanceService maintenanceService;
    private final IMaintenanceImportBaseService maintenanceImportBaseService;
    private final IMaintenanceImportDetailService maintenanceImportDetailService;

    /**
     * 导入excel数据
     *
     * @param bo
     * @return
     */
    public Boolean importExcel(MaintenanceImportBaseBo bo) {
        // 生成批次号
        final String batchNo = SerialGenerator.generator.nextId();
        bo.setBatchNo(batchNo);

        // excel 处理
        MyExcelResult<MaintenanceImportDetailVo> excelResult = MyExcelUtil.getImportExcelData(batchNo, bo.getExcelUrl(),
            new MaintenanceExcelListener(batchNo), MaintenanceImportDetailVo.class, true);

        if (null == excelResult) {
            return false;
        }

        // 更新主表状态
        if (excelResult.isSuccess()) {
            bo.setProcessStatus(ERecordConstant.COMMON_STATUS_SUCCESS);
        } else {
            bo.setProcessStatus(ERecordConstant.COMMON_STATUS_ERROR);
        }
        bo.setProcessMsg(excelResult.getAnalysis());
        bo.setAttachMsg(ERecordConstant.ATTACH_UPLOAD_STATUS_NO);
        // 入库主表
        if (this.maintenanceImportBaseService.insertByBo(bo)) {
            // 入库子表
            if (!excelResult.getList().isEmpty()) {
                if (!this.maintenanceImportDetailService.batchInsertVo(excelResult.getList())) {
                    return false;
                }
            }
        } else {
            return false;
        }

        if (excelResult.isSuccess() && !excelResult.getList().isEmpty()) {
            this.maintenanceService.batchInsert(excelResult.getList());
        }

        return true;
    }
}
